<?php
/**
 * Pownce APi Class for interacting with Pownce
 * Written by Kyle Browning[ocyrus]
 * 
 */
require_once('OAuth.php');
define('OAUTH_REQUEST_TOKEN_URL', 'http://api.pownce.com/2.0/oauth/request_token');
define('OAUTH_AUTHORIZE_URL', 'http://api.pownce.com/2.0/oauth/authorize');
define('OAUTH_ACCESS_URL', 'http://api.pownce.com/2.0/oauth/access_token');
define('OAUTH_VERIFY_URL', 'http://api.pownce.com/2.0/auth/verify.xml');
define('OAUTH_SENDMESSAGE_URL', 'http://api.pownce.com/2.0/send/message.xml');
define('OAUTH_SENDLIST_URL', 'http://api.pownce.com/2.0/send/send_to.xml');
define('OAUTH_SENDLINK_URL', 'http://api.pownce.com/2.0/send/link.xml');
define('OAUTH_SENDEVENT_URL', 'http://api.pownce.com/2.0/send/event.xml');
define('OAUTH_SENDFILE_URL', 'http://api.pownce.com/2.0/send/file.xml');
define('OAUTH_NOTELIST_URL', 'http://api.pownce.com/2.0/note_lists/');
class pownceAuth
{
  
  /**
   * Pownce Username Pase
   * ie. username:pass
   * @var base64_encode(string)
   */
  protected $pownce_userpass;
  
  
  /**
   * Pownce Headers
   * Authentication Basic base64 ecodeded username:pass
   * @var array
   */
  protected $headers;
  
  /**
   * Pownce Post options 
   * ie. app_key=appkey&note_to=publix&note_body=Hi
   * @var string
   */
  protected $options;
  /**
   * Our Curl object
   *
   * @var object
   */
  protected $curl_handler;
  
  /**
   * Our Response
   *
   * @var XML,JSON
   */
  protected $response;
  /**
   * our type POST, GET
   *
   * @var string
   */
  protected $type;
  
  /**
   * Authetnication Method
   * oAuth, Basic
   * 
   * @var strin
   */
  protected $auth_method;
  
  /**
   * Our signature method
   * For now, HMAC-SHA1
   *
   * @var object
   */
  protected $signature_method;
  
  /**
   * OAuth Consumer
   *
   * @var object
   */
  protected $consumer;
  
  /**
   * Current Request Object
   *
   * @var object
   */
  protected $request;
  
  /**
   * Current Access Token Information
   *
   * @var object
   */
  protected $access_token;
  
  /**
   * Current Request Token Information
   *
   * @var object
   */
  protected $request_token;
  
  /**
   * Page to Call
   *
   * @var string
   */
  protected $api_call;
  
  /**
   * Callback URL for use with Pownce
   *
   * @var string
   */
  protected $callback_url;
  
  /**
   * Our construct method, initializes our Pownce Object
   *
   */
  public function __construct($type = null)
  {
    switch (strtolower($type)) 
    {
      case 'oauth':
        $this->initOauth();
        break;
      default:
        $this->initBasic();
        break;
    }
  }
    /**
   * Set a bunch of variables to null
   *
   */
  protected function initOauth() 
  {
    $this->callback_url         = 'http://' . $_SERVER['HTTP_HOST'];
    $this->type                 = null;
    $this->curl_handler         = curl_init();
    $this->headers              = array();
    $this->api_call             = null;
    $this->consumer             = null;
    $this->request              = null;
    $this->response             = null;
    $this->auth_method          = 'oauth';
    $this->signature_method     = new OAuthSignatureMethod_HMAC_SHA1();
  }
  /**
   * Sets all values to defaults on construct.
   *
   */
  protected  function initBasic()
  {
    $this->pownce_address       = null;
    $this->pownce_userpass      = null;
    $this->pownce_datasource    = null;
    $this->headers              = array();
    $this->options              = null;
    $this->curl_handler         = curl_init();
    $this->type                 = null;
    $this->auth_method          = 'basic';
  }
    
  /**
   * Sets our curl object options
   *
   */
  public function initCurl()
  {
    curl_setopt($this->getPownceCurlHandler(), CURLOPT_RETURNTRANSFER, true);
    curl_setopt($this->getPownceCurlHandler(), CURLOPT_HTTPHEADER, $this->getPownceHeaders());
    //print 'HERE' . $this->getPownceApiCall() . 'There' .$this->getPownceType() . 'WITH'. $this->getPownceOptions().'<br>';
    if($this->getPownceType() == 'GET')
    {
      if($this->getPownceOptions())
      {
        curl_setopt($this->getPownceCurlHandler(), CURLOPT_URL, $this->getPownceApiCall() . '?'. $this->getPownceOptions());
      }
      else 
      {
        curl_setopt($this->getPownceCurlHandler(), CURLOPT_URL, $this->getPownceApiCall() . '?'. $this->getPownceOptions());
      }
      
    }
    else 
    {
      curl_setopt($this->getPownceCurlHandler(), CURLOPT_URL, $this->getPownceApiCall());
      curl_setopt($this->getPownceCurlHandler(), CURLOPT_POST, 1);
      curl_setopt($this->getPownceCurlHandler(), CURLOPT_POSTFIELDS, $this->getPownceOptions());
    }
  }
  
  
  /**
   * Executes our curl object
   *
   */
  public function execCurl()
  {
    $this->initCurl();
    $this->setPownceResponse(curl_exec($this->curl_handler));
    //print_r(curl_getinfo($this->getPownceCurlHandler()));
    curl_close($this->getPownceCurlHandler());
    $this->setPownceCurlHandler(curl_init());
    $this->setPownceOptions('');
  }

  /**
   * Static function to build a token
   *
   * @param string $token
   * @param string $token_secret
   * @return object
   */
  public static function buildToken($token, $token_secret) 
  {
    return new OAuthToken($token, $token_secret);
  }
  
  /**
   * Builds out our consumer for oAuth
   *
   * @param string $key
   * @param string $secret
   */
  public function buildConsumer($key, $secret) 
  {
    $this->setOauthConsumer(new OAuthConsumer($key, $secret, NULL));
  }
  
  /**
   * Builds out a request token
   *
   * @return array
   */
  public function getNewRequestToken() 
  {
    $this->setPownceType('POST');
    $this->setPownceApiCall(OAUTH_REQUEST_TOKEN_URL);
    $this->setOauthRequest(OAuthRequest::from_consumer_and_token($this->getOauthConsumer(), NULL, strtoupper($this->getPownceType()), $this->getPownceApiCall(), array()));
    $this->getOauthRequest()->sign_request($this->getOauthSignatureMethod(), $this->getOauthConsumer(), NULL);
    $this->setPownceHeaders($this->request->to_header());
    $this->execCurl();
    $oauth_token = $this->buildOauthInfo($this->getPownceResponse());
    $this->setOauthRequestToken(self::buildToken($oauth_token['oauth_token'],$oauth_token['oauth_token_secret']));
    return $this->buildOauthInfo($this->getPownceResponse());
  }
  /**
   * Gives us our URL to authorize the tokens with pownce
   *
   * @return string
   */
  public function getOauthAuthorizeUrl() 
  {
    $token = $this->getOauthRequestToken();
    if($this->getOauthCallbackUrl() != '')
    {
      $oauthAuthUrl = OAUTH_AUTHORIZE_URL .'?oauth_token='. $token->key .'&oauth_calback='. $this->getOauthCallbackUrl();
    }
    else 
    {
      $oauthAuthUrl = OAUTH_AUTHORIZE_URL .'?oauth_token='. $token->key;
    }
    return $oauthAuthUrl;
  }
  /**
   * Actually setup our authorize tokens to get an access token
   *
   * @param string $token
   * @param string $token_secret
   * @return array
   */
  public function getNewOauthAccessToken($token, $token_secret)
  {
    $this->setOauthAccessToken(self::buildToken($token, $token_secret));
    $this->setPownceApiCall(OAUTH_ACCESS_URL);
    $this->setPownceType('GET');
    $this->setOauthRequest(OAuthRequest::from_consumer_and_token($this->getOauthConsumer(), $this->getOauthAccessToken(), self::getPownceType(), $this->getPownceApiCall(), array()));
    $this->getOauthRequest()->sign_request($this->getOauthSignatureMethod(), $this->getOauthConsumer(), $this->getOauthAccessToken());
    $this->setPownceHeaders($this->getOauthRequest()->to_header());
    $this->execCurl();
    return $this->buildOauthInfo($this->getPownceResponse());
  }
  /**
   * Function for verifying our access tokens
   *
   * @param string $token
   * @param token_secret
   * @return boolean
   */
  public function verifyOauthAccess($token, $token_secret)
  {
      $this->setOauthAccessToken($this->buildToken($token, $token_secret));
      $this->setPownceType('GET');
      $this->setPownceApiCall(OAUTH_VERIFY_URL);
      $this->setOauthRequest(OAuthRequest::from_consumer_and_token($this->getOauthConsumer(), $this->getOauthAccessToken(), $this->getPownceType(), $this->getPownceApiCall()));
      $this->getOauthRequest()->sign_request($this->getOauthSignatureMethod(), $this->getOauthConsumer(), $this->getOauthAccessToken());
      $this->setPownceHeaders($this->getOauthRequest()->to_header());
      $this->execCurl();
      $xml_response = new SimpleXMLElement($this->getPownceResponse());
      if (is_object($xml_response)) {
        $response_key = $xml_response->app->key;
        $return = $response_key == $this->getOauthConsumer()->key ? TRUE : FALSE;
      }
      else {
        $return = FALSE;
      }
      return $return;
  }

  /**
   * Provides a method of building out returned data from pownce
   * Specifically for use with Token information
   *
   * @param string $oauth_response
   * @return array
   */
  private function buildOauthInfo($oauth_response) 
  {
    $builtOauth = array();
    $oauth_response = split('&',$oauth_response);
    foreach ($oauth_response as $line) {
      $temp = split('=', $line);
      $builtOauth[$temp[0]] = $temp[1];
    }
    return $builtOauth;
  }


  /**
   * Get POwnce UserPass 
   *
   * @return String
   */
  public function getPownceUserPass()
  {
    return $this->pownce_userpass;
  }

  
  /**
   * Get Pownce Headers
   *
   * @return array
   */
  public function getPownceHeaders()
  {
    return $this->headers;
  }
  
  /**
   * get Pownce PostOptions
   *
   * @return string
   */
  public function getPownceOptions()
  {
    return $this->options;
  }
  
  /**
   * Get Curl Handler Object
   *
   * @return object
   */
  public function getPownceCurlHandler()
  {
    return $this->curl_handler;
  }
  /**
   * Get Pownce Resource
   *
   * @return unknown
   */
  public function getPownceResponse()
  {
    return $this->response;
  }
  /**
   * Get POwnce Type
   *
   * @return string
   */
  public function getPownceType()
  {
    return $this->type;
  }
  
  public function getPownceApiCall()
  {
    return $this->api_call;
  }
  
  public function getOauthRequestToken() 
  {
    return $this->request_token;
  }
  public function getOauthConsumer() 
  {
    return $this->consumer;
  }
  public function getOauthCallbackUrl() 
  {
    return $this->callback_url;
  }
  public function getOauthRequest()
  {
    return $this->request;
  }
  
  public function getOauthSignatureMethod()
  {
    return $this->signature_method;
  }
  public function getOauthAccessToken()
  {
    return $this->access_token;
  }

  /**
   * Set Pownce UserPass
   *
   * @param string $value
   */
  public function setPownceUserPass($value)
  {
    $this->pownce_userpass = $value;
  }
  
  
  /**
   * Set Pownce headers
   *
   * @param string $value
   */
  public function setPownceHeaders($value)
  {
    $this->headers = array($value);
  }
  
  /**
   * Set Pownce Post Options
   *
   * @param unknown_type $value
   */
  public function setPownceOptions($value, $dontencode = false)
  {
    if($dontencode)
    {
      $this->options = $value;
    }
    else 
    {
      $this->options = urlencode($value);
    }
    
  }
  
  /**
   * Set Pownce Curl Handler
   *
   */
  public function setPownceCurlHandler()
  {
    $this->curl_handler = curl_init();
  }
  
  /**
   * Set Pownce Response
   *
   * @param String $value
   */
  public function setPownceResponse($value)
  {
    $this->response = $value;
  }
  /**
   * Set pownce Type
   *
   * @param string $value
   */
  public function setPownceType($value)
  {
    $this->type = $value;
  }
  public function setPownceApiCall($value)
  {
    $this->api_call = $value;
  }
  public function setOauthRequest($value) 
  {
    $this->request = $value;
  }
  public function setOauthConsumer($value)
  {
    $this->consumer = $value;
  }
  public function setOauthAccessToken($value)
  {
    $this->access_token = $value;
  }
  public function setOauthRequestToken($value) 
  {
    $this->request_token = $value;
  }
  public function setOauthCallbackUrl($value, $append)
  {
    if(isset($append)) 
    {
      $this->callback_url = $this->getOauthCallbackUrl() . $value;
    }
    else 
    {
      $this->callback_url = $value;
    }
  }
}



?>